import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { Injectable } from '@nestjs/common';
import * as dayjs from "dayjs"
import { CacheRedisService } from 'src/cache-redis/cache-redis.service';
import { sendEmailDto } from 'src/dto/email.dto';
import { success, error } from 'src/utils/common';
@Injectable()
export class EmailService {
    constructor(
        private readonly mailerService: MailerService,
        private redis: CacheRedisService
    ) { }

    async sendEmailCode(data: sendEmailDto) {
        const code = await this.redis.get(data.email)
        if (code) {
            return error("邮件已经发送，请稍后重试", 503)
        }
        try {
            const code = Math.random().toString().slice(-6)
            await this.redis.set(data.email, code)
            const sendMailOptions: ISendMailOptions = {
                from: "roulerchat@vip.qq.com",
                to: data.email,
                subject: "用户邮箱验证",
                template: "code.ejs",
                context: {
                    code: code,
                    date: dayjs().format("YYYY-MM-DD-HH")
                }
            }
            await this.mailerService.sendMail(sendMailOptions)
            return success("发送成功")
        } catch (errorMsg) {
            return error('发送失败请稍后尝试')
        }
    }
}
